<template>
  <div class="container">
    <!-- 新增角色弹出层 -->
    <el-dialog
      :title="Object.keys(row).length > 0 ? '修改标签' : '新增标签'"
      :visible="showAddProject"
      width="25%"
      @close="close"
    >
      <!-- 表单 -->
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item v-if="!showSubject" label="所属学科">
          <el-select v-model="roleForm.subjectID" placeholder="请选择">
            <el-option
              v-for="items in subject"
              :key="items.value"
              :label="items.label"
              :value="items.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称">
          <el-input v-model="roleForm.tagName" />
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <span slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submitRole">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/tags.js'
export default {
  props: {
    subject: {
      type: Array,
      default: () => []
    },
    showAddProject: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: () => ({})
    },
    showSubject: {
      type: Boolean,
      default: false
    }

  },
  data () {
    return {
      roleForm: {
        subjectID: '',
        tagName: ''
      },
      rules: {
        name: [
          { required: true, message: '标签不能为空', trigger: 'blur' },
          // 生效
          { min: 2, max: 10, message: '标签长度为2~10位', trigger: 'blur' }
        ]
      }
    }
  },
  // ------------------------------------------------
  watch: {
    row (newValue) {
      if (newValue) {
        this.roleForm = {
          subjectID: newValue.subjectID,
          tagName: newValue.tagName
        }
      }
    }
  },
  // ------------------------------------------------------
  methods: {
    // 修改数据---------------------------------------
    close () {
      this.$refs.roleForm.resetFields()
      this.roleForm = {
        subjectID: '',
        tagName: ''
      }
      this.$emit('closeD')
    },
    // 新增数据
    async submitRole () {
      console.log(Object.keys(this.row).length)
      if (Object.keys(this.row).length > 0) {
        await update({ ...this.roleForm, id: this.row.id })
        this.$message.success('修改成功')
      } else {
        await add(this.roleForm)
        this.$message.success('添加成功')
      }
      this.close()
    }

  }
}
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
